Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

support for enum type of db /支持 数据库 enum #1753

Closed
wants to merge 1 commit into from

Conversation

liuweizzuie
Copy link

hello there,

here we have an entity like this:

    public enum ContentType
    {
        TXT,

        MD,

        HTML
    }

    [Table("card")]
    public class Card: BaseEntityUInt64
    {
        [Column("uid")]
        public ulong UID { get; set; }

        [Column("create_at")]
        public DateTime CreateAt { get; set; }

        [Column("title")]
        public string Title { get; set; }

        [Column("content")]
        public string Content { get; set; }

        [Column("content_type")]
        public ContentType ContentType { get; set; }

        public Card()
        {
            this.Title = string.Empty;
            this.Content = string.Empty;
            this.ContentType = ContentType.TXT;
        }
    }

and the table defines like :

CREATE TABLE `card` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT 'ID服务中心获取ID,以便将来分库',
  `uid` bigint(20) DEFAULT NULL,
  `create_at` datetime DEFAULT NULL,
  `title` varchar(128) DEFAULT NULL,
  `content` text,
  `content_type` enum('TXT','MD','HTML') NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `id_UNIQUE` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci

we want to support enum type for database, via TypeHandler:

    public class EnumTypeHandler<T> : SqlMapper.TypeHandler<T> where T : struct, IConvertible
    {
        static EnumTypeHandler()
        {
            if (!typeof(T).IsEnum)
            {
                throw new ArgumentException("T must be an enumeration type");
            }
        }

        public override T Parse(object value)
        {
            return (T)Enum.Parse(typeof(T), Convert.ToString(value));
        }

        public override void SetValue(IDbDataParameter parameter, T value)
        {
            parameter.Value = value.ToString();
            parameter.DbType = DbType.AnsiString;
        }
    }

we use
SqlMapper.AddTypeHandler(typeof(ContentType), new EnumTypeHandler<ContentType>());

but it doesn't work.

so I forked the repository and made a little change.

please consider this.

@liuweizzuie
Copy link
Author

sorry for the confict , i will fix it

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant